from public.UDP_connect import udp_server
import time
from config.config import master_ip,server_ip,trigger_multiip,dport,server_port

def trigger(trigger_switch,trigger_pattern):
    try:
        my_eb = udp_server(server_ip, server_port)  # PC IP
        my_eb.open()

        time_delay = 2  # 触发延迟
        eb_read = [0x4e, 0x5f, 0x10, 0x44, 0xa0, 0x0f,
                   0x00, 0x02, 0x00, 0x00, 0x80, 0x02,
                   0x00, 0x02, 0x03, 0x04, 0x00, 0x02,
                   0x03, 0x08, 0xe8, 0x0f, 0x00, 0x01,
                   0x00, 0x00, 0x80, 0x03, 0x00, 0x00,
                   0x00, 0x04]  # Etherbone包，从Master读取当前的WR时间
        my_eb.sent_message(eb_read, master_ip, dport)
        rd = my_eb.receive_message()  # 接收Master返回的WR时间

        utc_sec = rd[23] * 256 * 256 * 256 * 256 + rd[16] * 256 * 256 * 256 + rd[17] * 256 * 256 + rd[18] * 256 + rd[19]  # 解码WR时间
	
        init_time = utc_sec + time_delay  # 在当前WR时间基础上，添加延迟，生成触发开始时刻
        utc0 = init_time % 256
        utc1 = int(init_time / 256 % 256)
        utc_time = [0x00, 0x00, utc1, utc0, 0x00, 0x00, 0x00, 0x00]  # 生成触发时刻，utc0后的4个0x00是秒计数，可以修改
        print("utc_time:", utc_time)

        trigger_mode = 0x00
        if trigger_switch == 0x00 and trigger_pattern == 0x00:
            trigger_mode = 0x00
        elif trigger_switch == 0x01 and trigger_pattern == 0x00:
            trigger_mode = 0x10
        elif trigger_switch == 0x00 and trigger_pattern == 0x01:
            trigger_mode = 0x01
        elif trigger_switch == 0x01 and trigger_pattern == 0x01:
            trigger_mode = 0x11

        eb_write = [0x4e, 0x5f, 0x14, 0x44, 0x08, 0x0f,
                    0x02, 0x00, 0x00, 0x02, 0x07, 0x00,
                    0x00, utc1, utc0, trigger_mode, 0x00, 0x00,
                    0x00, 0x90]  # 生成开始触发的Etherbone包
        my_eb.sent_message(eb_write, trigger_multiip, dport)  # 发送多播的触发包

    finally:
        print("close!")
        my_eb.close()
# 连续触发
def trigger_coiled():
    trigger_switch = 0x01  # 触发开关
    trigger_pattern = 0x01  # 触发模式
    trigger(trigger_switch,trigger_pattern)


# 单次触发
def trigger_single():
    trigger_switch = 0x01  # 触发开关
    trigger_pattern = 0x00  # 触发模式
    trigger(trigger_switch,trigger_pattern)


# 触发关闭
def trigger_close():
    trigger_switch = 0x00  # 触发开关
    trigger_pattern = 0x01  # 触发模式
    trigger(trigger_switch,trigger_pattern)
